import { useRef, useState } from "react";
import { message, Modal } from "antd";

import { RecordDetail } from "../type";
import ResourceForm from "@/views/AuthManage/ResourceManage/ResourceForm";

interface Props {
	detail?: RecordDetail;
	editText?: string;
	onEdit: (values: RecordDetail) => Promise<any>;
}

const EditResourceModal: React.FC<Props> = ({ detail, editText = "编辑", onEdit }) => {
	const [open, setOpen] = useState(false);
	const resourceFormRef = useRef<any>(null);

	const handleOk = async () => {
		try {
			const values = await resourceFormRef.current.validateFields();
			onEdit(values).then(res => {
				if (res?.code === 0) {
					handleCancel();
				}
			});
		} catch (error) {
			message.warn("信息填写有误！");
		}
	};
	const handleCancel = () => {
		setOpen(false);
	};

	return (
		<>
			<div className="link" onClick={() => setOpen(true)}>
				{editText}
			</div>
			{open && (
				<Modal
					title="修改资源名称"
					destroyOnClose
					maskClosable={false}
					width={660}
					open={open}
					onOk={handleOk}
					onCancel={handleCancel}
				>
					<ResourceForm ref={resourceFormRef} selRecord={detail}></ResourceForm>
				</Modal>
			)}
		</>
	);
};
export default EditResourceModal;
